﻿using EnterpriseWebsiteApi.ActionFilters;
using EnterpriseWebsiteApi.ActionResults;
using EnterpriseWebsiteApi.Dto;
using EnterpriseWebsiteApi.Dto.AboutUs;
using EnterpriseWebsiteApi.Dto.Article;
using EnterpriseWebsiteBLL;
using EnterpriseWebsiteEntity;
using EnterpriseWebsiteUtil.Helper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace EnterpriseWebsiteApi.Controllers.Admin
{
  [Route("api/admin/[controller]/[action]")]
  [ApiController]
  [TypeFilter(typeof(JwtAuthorizeFilter))]
  public class ArticleController : ControllerBase
  {
    private readonly ArticleService _articleService;
    private readonly Mapper _mapper;

    public ArticleController(ArticleService articleService, Mapper mapper)
    {
      _articleService = articleService;
      _mapper = mapper;
    }

    /// <summary>
    /// 获取所有文章
    /// </summary>
    [HttpGet]
    public async Task<ActionResult> GetAll(int pageIndex = 0, int pageSize = 20, int category = 0, string keyword = null)
    {
          try
          {
                TablePageDto<ArticleListQueryDto> tablePageDto = new TablePageDto<ArticleListQueryDto>();
                RefAsync<int> toalNumber = 0;
                var entities = await _articleService.GetAllArticlesAsync(toalNumber, pageIndex, pageSize, category, keyword);
                tablePageDto.Data = _mapper.MapList<ArticleListQueryDto>(entities);
                tablePageDto.PageIndex = pageIndex;
                tablePageDto.PageSize = pageSize;
                tablePageDto.ToalNumber = toalNumber;
                return new Success(tablePageDto);
          }
          catch (Exception ex)
          {
                return new Error(ex);
          }
    }

    /// <summary>
    /// 根据id获取文章
    /// </summary>
    [HttpGet]
    public async Task<ActionResult> GetById(int id)
    {
      try
      {
        var entity = await _articleService.GetArticleByIdAsync(id);
        if (entity == null)
        {
          throw new Exception("文章不存在");
        }
        var dto = _mapper.Map<ArticleSingleQueryDto>(entity);
        return new Success(dto);
      }
      catch (Exception ex)
      {
        return new Error(ex);
      }
    }

    /// <summary>
    /// 添加文章
    /// </summary>
    /// <param name="dto">文章信息</param>
    [HttpPost]
    public async Task<ActionResult> Add(ArticleCreateDto dto)
    {
      try
      {
        var entity = _mapper.Map<ArticleEntity>(dto);
        await _articleService.AddArticleAsync(entity);
        return new Success();
      }
      catch (Exception ex)
      {
        return new Error(ex);
      }
    }

    /// <summary>
    /// 更新文章
    /// </summary>
    /// <param name="dto">文章信息</param>
    [HttpPost]
    public async Task<ActionResult> Update(ArticleUpdateDto dto)
    {
      try
      {
        var entity = await _articleService.GetArticleByIdAsync(dto.Id);
        if (entity == null)
        {
          throw new Exception("文章不存在");
        }
        entity = _mapper.Map(dto, entity);
        await _articleService.UpdateArticleAsync(entity);
        return new Success();
      }
      catch (Exception ex)
      {
        return new Error(ex);
      }
    }

    /// <summary>
    /// 删除文章
    /// </summary>
    /// <param name="id">文章id</param>
    [HttpGet]
    public async Task<ActionResult> Delete(int id)
    {
      try
      {
        var entity = await _articleService.GetArticleByIdAsync(id);
        if (entity == null)
        {
          throw new Exception("文章不存在");
        }
        await _articleService.DeleteArticleAsync(id);
        return new Success();
      }
      catch (Exception ex)
      {
        return new Error(ex);
      }
    }

    /// <summary>
    /// 批量删除文章
    /// </summary>
    /// <param name="array"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<ActionResult> DeleteBatch(int[] array)
    {
      try
      {
        await _articleService.DeleteArticleBatchAsync(array);
        return new Success();
      }
      catch (Exception ex)
      {
        return new Error(ex);
      }
    }

    /// <summary>
    /// 媒体上传
    /// </summary>
    /// <param name="mediaFile"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<ActionResult<WangEditorUploadDto>> UploadMedia(IFormFile mediaFile)
    {
      try
      {
        string directoryName = "article";
        WangEditorUploadDataDto editorUploadData = new WangEditorUploadDataDto();

        if (mediaFile == null)
        {
          return Ok(new WangEditorUploadDto() { errno = 1, message = "未有上传文件" });
        }

        string mediaType = Path.GetExtension(mediaFile.FileName).ToLower();

        if (mediaFile.Length > 5 * 1024 * 1024)
        {
          return Ok(new WangEditorUploadDto() { errno = 1, message = "上传的文件大小不能超过5mb" });
        }
        if (mediaType.StartsWith(".jpg") || mediaType.StartsWith(".jpeg") || mediaType.StartsWith(".png"))
        {
          if (mediaFile.Length > 2 * 1024 * 1024)
          {
            return Ok(new WangEditorUploadDto() { errno = 1, message = "上传的图片不能大于2mb" });
          }
        }

        string fileName = $"{Guid.NewGuid()}{mediaType}";
        string folderPath = Path.Combine("wwwroot", directoryName);
        string filePath = Path.Combine("wwwroot", directoryName, fileName);

        if (!Directory.Exists(folderPath))
        {
          Directory.CreateDirectory(folderPath);
        }

        using (FileStream stream = new FileStream(filePath, FileMode.Create))
        {
          await mediaFile.CopyToAsync(stream);
        }

        string baseUrl = $"{Request.Scheme}://{Request.Host}{Request.PathBase}";
        string mediaUrl = $"/{directoryName}/{fileName}";
        editorUploadData.url = $"{baseUrl}{mediaUrl}";
        return Ok(new WangEditorUploadDto() { errno = 0, data = editorUploadData });
      }
      catch (Exception ex)
      {
        return Ok(new WangEditorUploadDto() { errno = 1, message = ex.ToString() });
      }
    }

    /// <summary>
    /// 改变文章显示状态
    /// </summary>
    /// <param name="id"></param>
    /// <param name="display"></param>
    /// <returns></returns>
    [HttpGet]
    public async Task<ActionResult> ChangeDisplay(int id, bool display)
    {
      try
      {
        await _articleService.ChangeDisplay(id, display);
        return new Success();
      }
      catch (Exception ex)
      {
        return new Error(ex);
      }
    }
  }
}
